package com.hnx.admin.common.security.utils;

import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hnx.admin.api.http.HttpStatusAPI;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/*
创建人： 倔强的头发
创建时间：2024/7/10
功能描述:

*/
@Component
public record JSONUtil(ObjectMapper objectMapper) implements HttpStatusAPI {
    public  void writeJSON(HttpServletResponse response, Map<String, Object> map) {
        try {
            // 检查输入的map是否为空，避免生成空的JSON字符串
            if (map == null || map.isEmpty()) {
                response.setStatus(HttpServletResponse.SC_NO_CONTENT); // 返回状态码 204 表示请求成功，但没有要返回的信息
                return;
            }

            String content = objectMapper.writeValueAsString(map);
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            if (StrUtil.isNotBlank(content)) {
                // 对write函数进行了异常捕获和处理
                try {
                    write(response, content);
                } catch (Exception e) {
                    // 返回一个标准化的错误响应，隐藏了具体的异常信息，避免了信息泄露的风险
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                }
                finally {
                    RequestContextHolderUtil.clear();
                }
            }
        } catch (IOException ex) {
            // 对于序列化过程中可能出现的异常进行捕获和处理
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (Exception ex) {
            // 对于其他类型的异常，也可以进行类似的处理
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
    public  void write(HttpServletResponse response, String text) throws UtilException {
        Writer writer = null;
        try {
            writer = response.getWriter();
            if (writer != null) {
                BufferedWriter bufferedWriter = new BufferedWriter(writer);
                bufferedWriter.write(text);
                bufferedWriter.flush();
            }
        } catch (IOException e) {
            throw new UtilException(e);
        } finally {
            if (writer != null) {
                IoUtil.close(writer);
            }
        }
    }
    // 使用泛型来增强类型安全，同时返回一个不可变的Map以增强线程安全和封装性
    private  Map<String, Object> getJson(Integer code,String msg) {
        // 使用Collections.unmodifiableMap返回一个不可修改的Map
        Map<String, Object> map = new ConcurrentHashMap<>();
        map.put(CODE_TAG,code);
        map.put(MSG_TAG,msg);
        return Collections.unmodifiableMap(map);
    }
    public  void printFail(HttpServletRequest request, HttpServletResponse response, Integer code, String msg) {
        writeJSON(response, getJson(code,msg));
    }
    public  void printFail(HttpServletRequest request, HttpServletResponse response, String msg) {
        printFail(request,response,DEFAULT_HTTP_ERROR_CODE,msg);
    }
}
